import wtforms
from wtforms.validators import Email, Length, EqualTo, InputRequired
from models.auth import UserModel, EmailCaptchaModel

class RegistrationForm(wtforms.Form):
    email = wtforms.StringField(validators=[Email(message='邮箱不正确')])
    captcha = wtforms.StringField(validators=[Length(min=4, max=4, message='验证码格式不正确')])
    username = wtforms.StringField(validators=[Length(min=1, max=10, message='用户名不正确')])
    password = wtforms.StringField(validators=[Length(min=4, max=20, message='密码格式不正确')])
    confirm_password = wtforms.StringField(validators=[EqualTo('password', message='密码不一致')])

    def validate_email(self, field):
        if UserModel.query.filter_by(email=field.data).first():
            raise wtforms.ValidationError(message='邮箱已被注册')

    def validate_captcha(self, field):
        captcha = field.data
        email = self.email.data

        captcha_model = EmailCaptchaModel.query.filter_by(email=email, captcha=captcha).first()
        if not captcha_model:
            raise wtforms.ValidationError(message='验证码错误')

class LoginForm(wtforms.Form):
    email = wtforms.StringField(validators=[Email(message='邮箱格式不正确')])
    password = wtforms.StringField(validators=[Length(min=4, max=20, message='密码格式不正确')])

class QuestionForm(wtforms.Form):
    title = wtforms.StringField(validators=[Length(min=1, max=100, message='标题格式不正确')])
    content = wtforms.StringField(validators=[Length(min=1, message='内容格式不正确')])

class AnswerForm(wtforms.Form):
    content = wtforms.StringField(validators=[Length(min=1, max=100, message='内容格式不正确')])
    question_id = wtforms.IntegerField(validators=[InputRequired(message='question_id必传')])